//
//  IWHomeViewController.m
//  SINA
//
//  Created by 王相超 on 16/3/28.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

#import "IWHomeViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "IWTitleButton.h"
#import "IWTemp2Ctll.h"
#import "IWPopView.h"
#import <AFNetworking.h>
#import "IWAccoutTool.h"
#import "IWAccount.h"
#import "IWUserModel.h"
#import <MJExtension.h>
#import "IWStatusModel.h"
#import "IWLoadMoreView.h"

@interface IWHomeViewController ()

@property(strong,nonatomic)NSMutableArray *statusArr;

@end

@implementation IWHomeViewController

-(NSMutableArray *)statusArr{
    
    if (_statusArr == nil) {
        _statusArr = [NSMutableArray array];
    }
    
    return _statusArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNav];
    
    [self setupRefresh];
    
    [self gerUserInfo];
    
}

//刷新控件
- (void)setupRefresh{
    
    UIRefreshControl *control = [[UIRefreshControl alloc] init];
    
    [self.tableView addSubview:control];
    
    //监听事件
    [control addTarget:self action:@selector(loadNewStatus:) forControlEvents:UIControlEventValueChanged];
    
    [control beginRefreshing];
    
    [self loadNewStatus:control];
    
    IWLoadMoreView * loadMore = [IWLoadMoreView loadMoreView];
    
    self.tableView.tableFooterView = loadMore;
    
    loadMore.hidden = YES;
}

//设置导航栏内容
-(void)setNav{
    
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" target:self action:@selector(friendSearch)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" target:self action:@selector(pop)];
    
    IWTitleButton *titleBtn = [[IWTitleButton alloc] init];
    
    NSString *screenName = [[NSUserDefaults standardUserDefaults] objectForKey:@"screen_name"];
    if (!screenName) {
        screenName = @"首页";
    }
    
    [titleBtn setTitle:screenName forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    //titleBtn.backgroundColor = [UIColor redColor];
    
    [titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [titleBtn sizeToFit];
    
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleBtn;
}


//弹出菜单
-(void)titleBtnClick:(UIButton *)sender{
    
    
    UIView *custom = [[UIView alloc] initWithFrame:CGRectMake(7, 12, 100, 100)];
    
    custom.backgroundColor = [UIColor redColor];
    
    IWPopView *pop = [[IWPopView alloc] initWithCustomView:custom];
    
    pop.size = [UIScreen mainScreen].bounds.size;
    
    [pop showWithView:sender];
    
}

//搜索框
-(void)friendSearch{
    
    IWTemp2Ctll *vc = [[IWTemp2Ctll alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)pop{
    
}

//请求个人信息

-(void)gerUserInfo{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *str = @"https://api.weibo.com/2/users/show.json";
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    IWAccount *account = [IWAccoutTool model];
    
    parameters[@"access_token"] = account.access_token;
    
    parameters[@"uid"] = account.uid;
    
    [manager GET: str parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        
        IWUserModel *model = [IWUserModel new];
        
        [model mj_setKeyValues:responseObject];
        
        NSString *screenName = model.screen_name;
        
        [[NSUserDefaults standardUserDefaults] setObject:screenName forKey:@"screenName"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        UIButton *titleBtn = (UIButton *)self.navigationItem.titleView;
        [titleBtn setTitle:screenName forState:UIControlStateNormal];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"请求是被:%@",error);
    }];
    
}

//获取微博
-(void)loadNewStatus:(UIRefreshControl *)refresh{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *str = @"https://api.weibo.com/2/statuses/friends_timeline.json";
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    IWAccount *account = [IWAccoutTool model];
    
    parameters[@"access_token"] = account.access_token;
    
    parameters[@"since_id"] = @([[self.statusArr firstObject] id]);
    
    
    [manager GET: str parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@",responseObject);
        
        [refresh endRefreshing];
        
        //字典数组
        NSArray *dictArr = responseObject[@"statuses"];
        //模型数组
        NSArray *status = [IWStatusModel mj_objectArrayWithKeyValuesArray:dictArr];
        
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, status.count)];
        
        [self.statusArr insertObjects:status atIndexes:set];
        
        //[self.statusArr addObjectsFromArray:status];
        
        [self.tableView reloadData];
        
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [refresh endRefreshing];
        NSLog(@"请求是被:%@",error);
    }];
    
}

//加载底部数据
-(void)loadMoreStatus{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *str = @"https://api.weibo.com/2/statuses/friends_timeline.json";
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    IWAccount *account = [IWAccoutTool model];
    
    parameters[@"access_token"] = account.access_token;
    
    parameters[@"max_id"] = @([[self.statusArr lastObject] id] - 1 );
    
    
    [manager GET: str parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@",responseObject);
        
        self.tableView.tableFooterView.hidden = YES;
        
        //字典数组
        NSArray *dictArr = responseObject[@"statuses"];
        //模型数组
        NSArray *status = [IWStatusModel mj_objectArrayWithKeyValuesArray:dictArr];
        
        //NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, status.count)];
        
        
        [self.statusArr addObjectsFromArray:status];
        
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
     
        NSLog(@"请求是被:%@",error);
    }];
    
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.statusArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *key = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:key];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:key];
    }
    
    IWStatusModel *model = self.statusArr[indexPath.row];
    
    cell.textLabel.text = model.text;
    
    return cell;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.statusArr.count == 0) {
        return;
    }
    
    if (self.tableView.tableFooterView.hidden == NO) {
        return;
    }
    
    CGFloat result = scrollView.contentSize.height - scrollView.height + self.tabBarController.tabBar.height - self.tableView.tableFooterView.height;
    
    if (result < scrollView.contentOffset.y) {
        
        self.tableView.tableFooterView.hidden = NO;
        [self loadMoreStatus];
    }
    
    
}


@end
